import 'dart:io';

import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/utils/file_util.dart';

// 版本更新提示弹框
class UpdateDialog extends StatefulWidget {
  const UpdateDialog({
    required this.version,
    required this.upDateContent,
    required this.isForce,
    required this.downloadAddress,
    super.key,
  });

  final String upDateContent;
  final bool isForce;
  final String version;
  final String downloadAddress;

  @override
  State<UpdateDialog> createState() => _UpdateDialogState();
}

class _UpdateDialogState extends State<UpdateDialog> {
  double _progress = 0; // 设置进度
  String filePath = ''; // 文件路径
  bool isExist = false; // 文件是否存在
  bool isDownLoad = false; // 是否正在下载

  @override
  void initState() {
    super.initState();
  }

  void init() async {
    // 获取文件路径
    filePath = await FileUtils.getSavePath(widget.downloadAddress);
    // 判断文件是否存在
    isExist = await File(filePath).exists();
    setState(() {});
  }

  /// 根据[_progress] 获取进度条
  Widget getProgressView() {
    return Visibility(
      visible: isDownLoad,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          children: [
            Text(
              '${(_progress * 100).toStringAsFixed(0)}%',
              style: const TextStyle(fontSize: 16, color: Colors.black54, decoration: TextDecoration.none),
            ),
            const SizedBox(
              height: 10,
            ),
            LinearProgressIndicator(
              value: _progress,
              backgroundColor: Colors.grey[200],
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
            ),
          ],
        ),
      ),
    );
  }

  //获取按钮显示
  Widget getButtonView() {
    return isExist
        ? Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: ElevatedButton(
              style: ButtonStyle(
                  minimumSize: MaterialStateProperty.all(const Size(0, 40)),
                  shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  )),
                  backgroundColor: MaterialStateProperty.all(const Color(0xff6EAFFA))),
              onPressed: downFile,
              // 设置按钮为圆角
              child: const Text(
                '立即体验',
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ),
          )
        : Container(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(const Size(0, 40)),
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(14.0),
                        )),
                        backgroundColor: MaterialStateProperty.all(Colors.red)),
                    child: const Text(
                      '重新下载',
                      style: TextStyle(fontSize: 18, color: Colors.white),
                    ),
                    onPressed: () async {
                      await FileUtils.delete(widget.downloadAddress);
                      downFile();
                    },
                  ),
                ),
                AppGaps.hGap10,
                Expanded(
                  child: ElevatedButton(
                    style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(const Size(0, 40)),
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(14.0),
                        )),
                        backgroundColor: MaterialStateProperty.all(const Color(0xff6EAFFA))),
                    onPressed: downFile,
                    child: const Text(
                      '安装使用',
                      style: TextStyle(fontSize: 18, color: Colors.white),
                    ),
                  ),
                )
              ],
            ));
  }

  void downFile() {
    FileUtils.downloadFile(
      isShowLoading: false,
      type: 'application/vnd.android.package-archive',
      widget.downloadAddress,
      onReceiveProgress: (int value, int total) {
        isDownLoad = value < total;
        // 更新下载进度
        _progress = value / total;
        setState(() {});
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            width: 300,
            height: 320,
            child: Stack(
              children: <Widget>[
                SizedBox(
                  width: double.infinity,
                  height: double.infinity,
                  child: Image.asset(
                    AppImages.icon_update_bg,
                    fit: BoxFit.fill,
                  ),
                ),
                SizedBox(
                  width: double.infinity,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        margin: const EdgeInsets.only(top: 90),
                        child: Text(
                          '发现新版本！(V${widget.version})',
                          style: const TextStyle(fontSize: 20, color: Colors.black, decoration: TextDecoration.none),
                        ),
                      ),
                      Expanded(
                          child: SingleChildScrollView(
                        child: Container(
                          margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                          child: Text(
                            widget.upDateContent,
                            style: const TextStyle(fontSize: 16, color: Colors.black54, decoration: TextDecoration.none),
                          ),
                        ),
                      )),
                      AppGaps.vGap10,
                      getProgressView(),
                      AppGaps.vGap10,
                      Visibility(visible: !isDownLoad, child: getButtonView()),
                      AppGaps.vGap10,
                    ],
                  ),
                ),
              ],
            ),
          ),
          widget.isForce
              ? Container()
              : GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                    width: 35,
                    height: 35,
                    margin: const EdgeInsets.only(top: 30),
                    child: SvgPicture.asset(
                      AppImages.icon_train_questions_answers,
                      colorFilter: const ColorFilter.mode(Color(0xFFA0A7B5), BlendMode.srcIn),
                    ),
                  ),
                ),
        ],
      ),
    );
  }
}
